import React, { useEffect, useState } from "react";
import { Button, Input, Form, Space, List, Select, Card } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import styles from './index.module.css'


interface MyComponentProps {
    bpmnInstance: any;
}

interface DefaultOptionType {
    value: string;
    label: string;
}

interface ExecutionListenerElement {
    $type: string;
    event: string;
    class?: string;
    expression?: string;
    delegateExpression?: string;
}

// 监听器配置
interface Listener {
    event: 'start' | 'end' | 'take';
    type: 'class' | 'expression' | 'delegateExpression';
    value: string;
}

// 任务配置组件
const ListenerConfigurationView: React.FC<MyComponentProps> = (props: any) => {
    const { bpmnInstance } = props;
    const { modeling, moddle, bpmnElement = {}, currentElement } = bpmnInstance;
    const [baseInfo, setBaseInfo] = useState<any>();
    const [listeners, setListeners] = useState<Listener[]>([]);

    useEffect(() => {
        setBaseInfo(bpmnElement.businessObject);
        if (bpmnElement.businessObject) {
            const extensionElements = bpmnElement.businessObject.extensionElements?.values || []
            const executionListeners = extensionElements.filter(
                (item: ExecutionListenerElement) => item.$type === 'flowable:ExecutionListener',
            )
            setListeners(executionListeners.map((listener: ExecutionListenerElement) => ({
                event: listener.event || getDefaultEvent(props.currentElement as Element),
                type: getListenerType(listener),
                value: getListenerValue(listener),
            })))
        } else {
            setListeners([])

        }
    }, [bpmnElement.businessObject]);
    useEffect(() => {
        updateListeners();
    }, [listeners]);
    // 更新xml，，只有更新value的时候所有的参数才会同时改变
    const updateListeners = () => {
        if (!bpmnElement || !modeling) return;
        // 创建新的监听器元素
        const executionListeners = listeners.map((listener) => {
            const listenerConfig: Record<string, unknown> = {
                event: listener.event,
            };

            switch (listener.type) {
                case 'class':
                    listenerConfig.class = listener.value;
                    break;
                case 'expression':
                    listenerConfig.expression = listener.value;
                    break;
                case 'delegateExpression':
                    listenerConfig.delegateExpression = listener.value;
                    break;
            }
            return moddle.create('flowable:ExecutionListener', listenerConfig);
        });

        // 获取或创建扩展元素
        let extensionElements = bpmnElement.businessObject.extensionElements;
        if (!extensionElements) {
            extensionElements = moddle.create('bpmn:ExtensionElements', { values: [] });
        }

        // 过滤掉旧的监听器
        const otherElements = (extensionElements.values || []).filter(
            (item: ExecutionListenerElement) => item.$type !== 'flowable:ExecutionListener',
        );

        // 更新扩展元素
        extensionElements.values = [...otherElements, ...executionListeners];

        // 更新属性
        modeling.updateProperties(bpmnElement, {
            extensionElements: extensionElements.values.length > 0
                ? extensionElements
                : undefined,
        });
    };
    // 增加按钮
    const handleListener = () => {
        setListeners(prevListeners => [
            ...prevListeners,
            {
                event: getDefaultEvent(bpmnElement),
                type: 'class',
                value: '',
            },
        ]);
    };

    const getDefaultEvent = (element: any) => {
        return element.$type === 'bpmn:SequenceFlow' ? 'take' : 'start';
    };

    // 获取监听器类型
    const getListenerType = (listener: ExecutionListenerElement): Listener['type'] => {
        if (listener.class) return 'class'
        if (listener.expression) return 'expression'
        if (listener.delegateExpression) return 'delegateExpression'
        return 'class'
    }

    // 获取监听器值
    const getListenerValue = (listener: ExecutionListenerElement): string => {
        return listener.class || listener.expression || listener.delegateExpression || ''
    }
    // 删除
    const handleRemoveListener = (index: number) => {
        setListeners(prevListeners => prevListeners.filter((_, i) => i !== index));
    };
    // 监听事件类型改变
    const handleEventChange = (index: number, event: 'start' | 'end' | 'take') => {
        setListeners(prevListeners =>
            prevListeners.map((listener, i) =>
                i === index ? { ...listener, event } : listener
            )
        );
    };
    // 监听类型改变
    const handleTypeChange = (index: number, type: 'class' | 'expression' | 'delegateExpression') => {
        setListeners(prevListeners =>
            prevListeners.map((listener, i) =>
                i === index ? { ...listener, type } : listener
            )
        );
    };
    // 监听值改变更新监听器
    const handleValueChange = (index: number, value: string) => {
        setListeners(prevListeners =>
            prevListeners.map((listener, i) =>
                i === index ? { ...listener, value } : listener
            )
        );
    };
    const eventList: DefaultOptionType[] = [
        {
            value: "start",
            label: '开始',
        }, {
            value: "end",
            label: '结束',
        },
        // {
        //     value: "take",
        //     label: '制作',
        // },
    ]
    const typeList: DefaultOptionType[] = [
        {
            value: "class",
            label: 'Java类',
        }, {
            value: "expression",
            label: '表达式',
        },
        {
            value: "delegateExpression",
            label: '代理表达式',
        },
    ]
    return (
        <div className={styles.listenerContainer}>
            <Button type="primary" className={styles.ButtonClass} icon={<PlusOutlined />} onClick={handleListener}>
                添加监听器
            </Button>

            {listeners.length > 0 && (<>
                {listeners.map((listener, index) => (
                    <Card
                        className={styles.CardClass}
                        key={index} title={`监听器 ${index + 1}`}
                        extra={<Button type="link" onClick={() => handleRemoveListener(index)}>删除</Button>}
                    >
                        <Form>
                            <Form.Item
                                label="事件类型"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}>
                                <Select
                                    value={listener.event}
                                    onChange={(event: 'start' | 'end' | 'take') => handleEventChange(index, event)}
                                    options={eventList}
                                >
                                </Select>
                            </Form.Item>
                            <Form.Item
                                label="监听器类型"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}>
                                <Select
                                    value={listener.type}
                                    onChange={(type: 'class' | 'expression' | 'delegateExpression') => handleTypeChange(index, type)}
                                    options={typeList}
                                >
                                </Select>
                            </Form.Item>
                            <Form.Item
                                label="值"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}>
                                <Input
                                    value={listener.value}
                                    onChange={(e) => handleValueChange(index, e.target.value)}
                                />
                            </Form.Item>
                        </Form>
                    </Card>
                ))}
            </>)}
        </div>
    );
};

export default ListenerConfigurationView;
